const { default: BigNumber } = require('bignumber.js');
const { think } = require('thinkjs');
const Base = require('./base.js');
const cid = require('@4a/cid');
const moment = require('moment/moment.js');

module.exports = class extends Base {
  async detailAction() {
    const data = await this.model('post_list')
      .where({ id: this.get('id') })
      .find();
    // if (data.company) {
    //   data.company_num = data.company.split(',').length;
    // } else {
    //   data.company_num = false;
    // }

    // const companyInfo = await this.model('company_job')
    //   .where({ job_id: data.id })
    //   .distinct('city_name')
    //   .select();

    const companyInfo = await this.model('company_list')
      .where({ id: data.company })
      .field('avatar, name, city, scale, id, desc, fuli, address')
      .find();

    // if (!think.isEmpty(companyInfo)) {
    //   // companyInfo.sort((a, b) => a.money_end - b.money_end);
    //   // data.max = companyInfo[companyInfo.length - 1].money_end;

    //   data.citys = [];
    //   for (const item of companyInfo) {
    //     data.citys.push({
    //       city: item.city_name,
    //       // money_start: item.money_start,
    //       // money_end: item.money_end,
    //     });
    //   }
    // } else {
    //   data.citys = false;
    // }

    if (!think.isEmpty(companyInfo)) {
      if (companyInfo.fuli) {
        companyInfo.tags = await this.model('tag_list')
          .where({
            id: ['IN', companyInfo.fuli],
          })
          .field('name')
          .select();
      }
      data.companys = companyInfo;
    }

    const hasProcess = await this.model('process')
      .where({
        job_id: this.get('id'),
        user_id: this.getLoginUserId(),
      })
      .find();

    if (!think.isEmpty(hasProcess)) {
      data.hasProcess = hasProcess;
      data.interview_status = hasProcess.interview_status;
    }

    const userLike = await this.model('user_like')
      .where({ user_id: this.getLoginUserId(), job_id: this.get('id') })
      .find();

    if (!think.isEmpty(userLike)) {
      data.isLike = true;
    }

    const hasHistory = await this.model('user_history')
      .where({
        job_id: this.get('id'),
        user_id: this.getLoginUserId(),
      })
      .find();

    if (think.isEmpty(hasHistory)) {
      this.model('user_list')
        .where({ id: this.getLoginUserId() })
        .increment('history', 1);
      this.model('user_history').add({
        job_id: this.get('id'),
        user_id: this.getLoginUserId(),
        create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      });
    }

    const userJobs = this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .getField('jobs', true);

    userJobs.then((d) => {
      console.log(d, 9999);
      const arr = d.split(',');
      const isAdd = true;
      for (const item of arr) {
        if (item == this.get('id')) {
          isAdd = false;
        }
      }
      if (isAdd) {
        arr.push(this.get('id'));
        const str = arr.join(',');
        this.model('user_list')
          .where({ id: this.getLoginUserId() })
          .update({ jobs: str });
      }
    });

    const hasJob = await this.model('post_list').where({ id: this.get('id') });

    this.model('post_list')
      .where({ id: this.get('id') })
      .increment('view', 1);

    return this.success(data);
  }

  async getNameAction() {
    const data = await this.model('post_list')
      .where({ id: this.get('id') })
      .find();

    const user = await this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .find();
    data.user_name = user.name;

    return this.success(data);
  }

  async searchKeyAction() {
    const data = {};
    data.search = await this.model('user_search')
      .limit(5)
      .where({ user_id: this.getLoginUserId() })
      .order(['id DESC'])
      .select();

    data.hot = await this.model('post_list')
      .limit(5)
      .where({ status: 1, view: ['>', 50] })
      .field('name')
      .order(['view DESC'])
      .select();

    return this.success(data);
  }

  async cateAction() {
    const data = await this.model('post_category').where({ type: 1 }).select();
    for (const item of data) {
      const p = await this.model('post_category')
        .where({ type: 2, parent_id: item.id })
        .select();
      for (const itemP of p) {
        itemP.children = await this.model('post_category')
          .where({ type: 3, parent_id: itemP.id })
          .select();
      }
      item.children = p;
    }
    return this.success(data);
  }

  async cateAllAction() {
    const data = await this.model('post_category').where({ type: 1 }).select();
    return this.success(data);
  }

  async likeAction() {
    const id = this.get('id');
    const has = await this.model('user_like')
      .where({ job_id: id, user_id: this.getLoginUserId() })
      .find();
    let res;
    if (think.isEmpty(has)) {
      res = true;
      await this.model('user_like').add({
        job_id: this.get('id'),
        user_id: this.getLoginUserId(),
        create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      });
      this.model('user_list')
        .where({ id: this.getLoginUserId() })
        .increment('like', 1);
    } else {
      res = false;
      await this.model('user_like')
        .where({ job_id: id, user_id: this.getLoginUserId() })
        .delete();
      this.model('user_list')
        .where({ id: this.getLoginUserId() })
        .decrement('like', 1);
    }

    return this.success(res);
  }

  async tabListAction() {
    const type = this.get('type');
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const query = {
      'a.user_id': this.getLoginUserId() || 9159,
    };
    query['p.id'] = ['!=', null];
    if (type === '1') {
      const data = await this.model('user_history')
        .order(['a.id DESC'])
        .alias('a')
        .join({
          post_list: {
            join: 'left',
            as: 'p',
            on: ['job_id', 'id'],
          },
        })
        .distinct('a.job_id')
        .field('p.*, a.create_time as history_time')
        .where(query)
        .page(page, size)
        .countSelect();

      for (const item of data.data) {
        item.history_time = moment(item.history_time).format('MM-DD');
      }

      data.data = await this.model('index').getJobInfo(data.data);

      return this.success(data);
    } else if (type === '2') {
      query['a.interview_status'] = {
        '!=': null,
        '!=': 'INTERVIEW_FINISH',
      };
      // query['a.status'] = 3;
      const data = await this.model('process')
        .order(['a.id DESC'])
        .alias('a')
        .join({
          post_list: {
            join: 'left',
            as: 'p',
            on: ['job_id', 'id'],
          },
        })
        .field(
          'p.*, a.ordertoken, a.create_time as process_time, a.status as interview_status'
        )
        .where(query)
        .page(page, size)
        .countSelect();

      for (const item of data.data) {
        item.process_time = moment(item.process_time).format('MM-DD HH:mm');
      }

      data.data = await this.model('index').getJobInfo(data.data);

      return this.success(data);
    } else if (type === '4') {
      const data = await this.model('user_like')
        .order(['a.id DESC'])
        .alias('a')
        .join({
          post_list: {
            join: 'left',
            as: 'p',
            on: ['job_id', 'id'],
          },
        })
        .distinct('a.job_id')
        .field('p.*, a.create_time as like_time')
        .where(query)
        .page(page, size)
        .countSelect();

      for (const item of data.data) {
        item.like_time = moment(item.like_time).format('MM-DD');
      }

      data.data = await this.model('index').getJobInfo(data.data);

      return this.success(data);
    } else if (type === '3') {
      query['a.status'] = 3;
      const data = await this.model('process')
        .order(['a.id DESC'])
        .alias('a')
        .join({
          post_list: {
            join: 'left',
            as: 'p',
            on: ['job_id', 'id'],
          },
        })
        .field(
          'p.*, a.ordertoken, a.create_time as process_time, a.status as interview_status'
        )
        .where(query)
        .page(page, size)
        .countSelect();

      for (const item of data.data) {
        item.process_time = moment(item.process_time).format('MM-DD HH:mm');
      }

      data.data = await this.model('index').getJobInfo(data.data);

      return this.success(data);

      // const data = await this.model('company_interview')
      //   .order(['a.id DESC'])
      //   .alias('a')
      //   .join({
      //     company_list: {
      //       join: 'left',
      //       as: 'c',
      //       on: ['company_id', 'id'],
      //     },
      //     post_list: {
      //       join: 'left',
      //       as: 'p',
      //       on: ['job_id', 'id'],
      //     },
      //   })
      //   .field(
      //     'a.id as interviewId, a.user_id, a.status as interview_status, a.startTime, a.type, c.*, p.type as job_type, p.money_start, p.money_end, p.name as job_name'
      //   )
      //   .where(Object.assign(query, { 'a.status': ['NOTIN', '0,1'] }))
      //   .page(page, size)
      //   .countSelect();

      // for (const item of data.data) {
      //   if (item.fuli) {
      //     item.tags = await this.model('tag_list')
      //       .where({
      //         id: ['IN', item.fuli],
      //       })
      //       .field('name')
      //       .select();
      //   }
      //   item.startTime = moment(item.startTime * 1000).format('MM-DD HH:MM');
      // }

      // return this.success(data);
    }
  }
};
